<template>
  <div class="app-container">

    <h3>组卷信息</h3>
    <el-card style="margin-top: 20px">

      <div style="float: right; font-weight: bold; color: #ff0000">试卷总分：{{ postForm.totalScore }}分</div>

      <div>

        <el-button class="filter-item" v-if="repoList.length < 1" size="small" type="primary" icon="el-icon-plus"
          @click="handleAdd">
          添加题库
        </el-button>

        <el-table :data="repoList" :border="false" empty-text="请点击上面的`添加题库`进行设置" style="width: 100%; margin-top: 15px">
          <el-table-column label="题库" width="150">
            <template v-slot="scope">
              <repo-select v-model="scope.row.repoId" :multi="false" @change="repoChange($event, scope.row)" />
            </template>

          </el-table-column>
          <el-table-column label="单选数量" align="center">

            <template v-slot="scope">
              <el-input-number v-model="scope.row.radioCount" :min="0" :max="scope.row.totalRadio" :controls="false"
                style="width: 50px" /> / {{ scope.row.totalRadio }}
            </template>

          </el-table-column>

          <el-table-column label="单选分数" align="center">
            <template v-slot="scope">
              <el-input-number v-model="scope.row.radioScore" :min="0" :controls="false" style="width: 50px" />
            </template>
          </el-table-column>

          <el-table-column label="多选数量" align="center">

            <template v-slot="scope">
              <el-input-number v-model="scope.row.multiCount" :min="0" :max="scope.row.totalMulti" :controls="false"
                style="width: 50px" /> / {{ scope.row.totalMulti }}
            </template>

          </el-table-column>

          <el-table-column label="多选分数" align="center">
            <template v-slot="scope">
              <el-input-number v-model="scope.row.multiScore" :min="0" :controls="false" style="width: 50px" />
            </template>
          </el-table-column>

          <el-table-column label="判断题数量" align="center">

            <template v-slot="scope">
              <el-input-number v-model="scope.row.judgeCount" :min="0" :max="scope.row.totalJudge" :controls="false"
                style="width: 50px" /> / {{ scope.row.totalJudge }}
            </template>

          </el-table-column>

          <el-table-column label="判断题分数" align="center">
            <template v-slot="scope">
              <el-input-number v-model="scope.row.judgeScore" :min="0" :controls="false" style="width: 50px" />
            </template>
          </el-table-column>
          <el-table-column label="主观题数量" align="center">

            <template v-slot="scope">
              <el-input-number v-model="scope.row.saqCount" :min="0" :max="scope.row.totalSaq" :controls="false"
                style="width: 50px" /> / {{ scope.row.totalSaq }}
            </template>

          </el-table-column>

          <el-table-column label="主观题分数" align="center">
            <template v-slot="scope">
              <el-input-number v-model="scope.row.saqScore" :min="0" :controls="false" style="width: 50px" />
            </template>
          </el-table-column>

          <el-table-column label="删除" align="center" width="80px">
            <template v-slot="scope">
              <el-button type="danger" icon="el-icon-delete" circle @click="removeItem(scope.$index)" />
            </template>
          </el-table-column>

        </el-table>

      </div>

    </el-card>

    <h3>考试配置</h3>
    <el-card style="margin-top: 20px">

      <el-form ref="postForm" :model="postForm" :rules="rules" label-position="left" label-width="120px">

        <el-form-item label="考试名称" prop="examTitle">
          <el-input v-model="postForm.examTitle" />
        </el-form-item>

        <el-form-item label="考试描述" prop="examContent">
          <el-input v-model="postForm.examContent" type="textarea" />
        </el-form-item>

        <el-form-item label="总分数" prop="totalScore">
          <el-input-number :value="postForm.totalScore" disabled />
        </el-form-item>

        <el-form-item label="及格分" prop="qualifyScore">
          <el-input-number v-model="postForm.qualifyScore" :max="postForm.totalScore" />
        </el-form-item>

        <el-form-item label="考试时长(分钟)" prop="totalTime">
          <el-input-number v-model="postForm.totalTime" />
        </el-form-item>

        <el-form-item label="是否限时">
          <el-checkbox v-model="postForm.timeLimit" />
        </el-form-item>

        <el-form-item v-if="postForm.timeLimit" label="考试时间" prop="totalTime">

          <el-date-picker v-model="dateValues" format="yyyy-MM-dd" value-format="yyyy-MM-dd" type="daterange"
            range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" />

        </el-form-item>

      </el-form>

    </el-card>

    <!-- TODO: 设置为使用编号进入考试-->
    <h3>权限配置</h3>
    <el-card style="margin-top: 20px;">
      <el-alert title="若考试类型为 '指定人员参加考试'，请暂时保留此次考试信息，添加成功后，再做修改" type="warning" />
      <el-radio v-model="postForm.openType" :label=0>所有人参加考试</el-radio>
      <el-radio v-model="postForm.openType" :label=1>指定学生参加考试</el-radio>

      <el-alert v-if="postForm.openType == 0" title="开放的，任何人都可以在主页进行考试！" type="warning" />
      <div v-else>
        <el-alert title="私密的，只能通过搜索找到且指定人员考试" type="warning" />
        <div v-if="isUpdate">
          <el-button @click="() => { showImportList = true }">录入考生</el-button>
          <el-dialog :visible.sync="showImportList" title="考试设置" width="700px">
            <import-list v-model="postForm.id" @none="notEnterPerson($event)"></import-list>
          </el-dialog>
        </div>

      </div>

      <div style="margin-top: 20px;">
        <el-button type="warning" @click="() => { dialogVisible = true }">设置考试规则</el-button>
        <el-dialog :visible.sync="dialogVisible" title="考试设置" width="700px">
          <exam-conf v-if="examConf" :examData="examConf"></exam-conf>
        </el-dialog>
      </div>

    </el-card>


    <div style="margin-top: 20px">
      <el-button type="primary" @click="handleSave">保存</el-button>
    </div>

  </div>
</template>

<script>
import { fetchDetail, saveData } from '@/api/exam/exam'
import ImportList from '@/components/ImportToList'
import RepoSelect from '@/components/RepoSelect'
import ExamConf from '@/components/ExamConf'
export default {
  name: 'ExamDetail',
  components: { RepoSelect, ExamConf, ImportList },
  data() {
    return {
      examConf: {},
      defaultProps: {
        label: 'deptName'
      },
      showImportList: false,
      dialogVisible: false,
      filterText: '',
      treeLoading: false,
      dateValues: [],
      // 题库
      repoList: [],
      // 已选择的题库
      excludes: [],
      postForm: {
        // 总分数
        totalScore: 0,
        // 题库列表
        repoList: [],
        // 开放类型
        openType: 1,
        //时间限制
        timeLimit: false
      },
      isUpdate: false,
      rules: {
        examTitle: [
          { required: true, message: '考试名称不能为空！' }
        ],

        examContent: [
          { required: true, message: '考试名称不能为空！' }
        ],

        open: [
          { required: true, message: '考试权限不能为空！' }
        ],

        totalScore: [
          { required: true, message: '考试分数不能为空！' }
        ],

        qualifyScore: [
          { required: true, message: '及格分不能为空！' }
        ],

        totalTime: [
          { required: true, message: '考试时间不能为空！' }
        ],

        ruleId: [
          { required: true, message: '考试规则不能为空' }
        ],
        password: [
          { required: true, message: '考试口令不能为空！' }
        ]
      }
    }
  },

  watch: {

    dateValues: {

      handler() {
        this.postForm.startTime = this.dateValues[0]
        this.postForm.endTime = this.dateValues[1]
      }
    },

    // 题库变换
    repoList: {

      handler() {
        this.postForm.totalScore = 0
        this.excludes = []

        for (let i = 0; i < this.repoList.length; i++) {
          const item = this.repoList[i]
          this.postForm.totalScore += item.radioCount * item.radioScore
          this.postForm.totalScore += item.multiCount * item.multiScore
          this.postForm.totalScore += item.judgeCount * item.judgeScore
          this.postForm.totalScore += item.saqCount * item.saqScore
          this.excludes.push(item.id)
          // console.log('++++' + item.id)
        }

        // 赋值
        this.postForm.repoList = this.repoList
      },
      deep: true
    }

  },
  created() {
    const id = this.$route.params.id

    if (typeof id !== 'undefined') {

      this.isUpdate = true

      this.fetchData(id)
    } else {
      this.examConf = {
        openCamera: false,
        openWebChange: 0,
        difPaper: false,
        copyQu: false,
        stick: false,
      }
    }

  },
  methods: {

    handleSave(e) {
      this.$refs.postForm.validate((valid) => {
        if (!valid) {
          return
        }

        if (this.postForm.totalScore === 0) {
          this.$notify({
            title: '提示信息',
            message: '考试规则设置不正确，请确认！',
            type: 'warning',
            duration: 2000
          })

          return
        }

        for (let i = 0; i < this.postForm.repoList.length; i++) {
          const repo = this.postForm.repoList[i]
          if (!repo.repoId) {
            this.$notify({
              title: '提示信息',
              message: '考试题库选择不正确！',
              type: 'warning',
              duration: 2000
            })
            return
          }

          if ((repo.radioCount > 0 && repo.radioScore === 0) || (repo.radioCount === 0 && repo.radioScore > 0)) {
            this.$notify({
              title: '提示信息',
              message: '题库第：[' + (i + 1) + ']项存在无效的单选题配置！',
              type: 'warning',
              duration: 2000
            })

            return
          }

          if ((repo.multiCount > 0 && repo.multiScore === 0) || (repo.multiCount === 0 && repo.multiScore > 0)) {
            this.$notify({
              title: '提示信息',
              message: '题库第：[' + (i + 1) + ']项存在无效的多选题配置！',
              type: 'warning',
              duration: 2000
            })

            return
          }

          if ((repo.judgeCount > 0 && repo.judgeScore === 0) || (repo.judgeCount === 0 && repo.judgeScore > 0)) {
            this.$notify({
              title: '提示信息',
              message: '题库第：[' + (i + 1) + ']项存在无效的判断题配置！',
              type: 'warning',
              duration: 2000
            })
            return
          }
        }
        this.$confirm('确实要提交保存吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.submitForm()
        })
      })
    },

    // 添加子项
    handleAdd() {
      console.log(typeof this.repoList)
      this.repoList.push({ id: '', rowId: new Date().getTime(), radioCount: 0, radioScore: 0, multiCount: 0, multiScore: 0, judgeCount: 0, judgeScore: 0, saqCount: 0, saqScore: 0 })
    },

    removeItem(index) {
      this.repoList.splice(index, 1)
    },

    fetchData(id) {
      const params = {
        currentPage: 1,
        size: 10,
        id: id
      }

      fetchDetail(params).then(response => {
        this.postForm = response.data
        this.examConf = this.postForm.examConfig
        if (this.postForm.startTime && this.postForm.endTime) {
          this.dateValues[0] = this.postForm.startTime
          this.dateValues[1] = this.postForm.endTime
        }
        this.repoList = this.postForm.repoList

        console.log(this.repoList)
      })
    },

    submitForm() {
      // 校验和处理数据
      this.postForm.repoList = this.repoList;

      if (typeof this.postForm.createTime !== 'undefined') {
        this.postForm.createTime = new Date(this.postForm.createTime).getTime();

        this.postForm.updateTime = new Date(this.postForm.updateTime).getTime();

      } else {
        this.postForm.createTime = new Date().getTime();

        this.postForm.updateTime = new Date().getTime();
      }


      if (this.postForm.timeLimit) {
        this.postForm.startTime = new Date(this.postForm.startTime).getTime();

        this.postForm.endTime = new Date(this.postForm.endTime).getTime();
      }
      this.postForm.state = 0;
      this.postForm.userId = this.$store.state.user.userId;

      this.postForm.examConfig = this.examConf

      saveData(this.postForm).then(() => {
        this.$notify({
          title: '成功',
          message: '考试保存成功！',
          type: 'success',
          duration: 2000
        })
        this.$router.push({ name: 'ListExam' })
      })



    },
    notEnterPerson(e) {
      if (e && this.postForm.openType === 1) {
        this.$notify({
          title: '提示信息',
          message: '未录入考生',
          type: 'warning',
          duration: 2000
        })
        return
      }
    },


    repoChange(e, row) {

      console.log(row.id)

      console.log(e.id)
      // 赋值ID
      row.id = e.id
      if (e != null) {
        row.totalRadio = e.radioCount
        row.totalMulti = e.multiCount
        row.totalJudge = e.judgeCount
        row.totalSaq = e.saqCount
      } else {
        row.totalRadio = 0
        row.totalMulti = 0
        row.totalJudge = 0
        row.totalSaq = 0
      }
      console.log("row" + row.totalJudge)
    },
  }
}
</script>

